﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Converters;


public class ListToDataTableConverter
{
    public DataTable ListToDataTable<T>(List<T> items)
    {
        var dataTable = new DataTable(typeof(T).Name);

        // 获取对象 T 的所有公共实例属性
        var Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        //添加列名
        foreach (var prop in Props)
        {
            //DataColumn column = new();
            //column.ColumnName = prop.Name;
            //column.DataType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;

            //Setting column names as Property names
            DataColumn column = new(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

            dataTable.Columns.Add(column);
        }

        //添加行数据
        foreach (var item in items)
        {
            var row = dataTable.NewRow();

            foreach (var prop in Props)
            {

                row[prop.Name] = prop.GetValue(item, null) ?? DBNull.Value;


            }
            dataTable.Rows.Add(row);
        }
        //put a breakpoint here and check datatable
        return dataTable;
    }


    public DataTable ListToDataTable<T>(List<T> items, string _tableName)
    {
        var dataTable = new DataTable(_tableName);

        // 获取对象 T 的所有公共实例属性
        var Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        //添加列名
        foreach (var prop in Props)
        {
            //DataColumn column = new();
            //column.ColumnName = prop.Name;
            //column.DataType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;

            //Setting column names as Property names
            DataColumn column = new(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

            dataTable.Columns.Add(column);
        }

        //添加行数据
        foreach (var item in items)
        {
            var row = dataTable.NewRow();

            foreach (var prop in Props)
            {

                row[prop.Name] = prop.GetValue(item, null) ?? DBNull.Value;


            }
            dataTable.Rows.Add(row);
        }
        //put a breakpoint here and check datatable
        return dataTable;
    }

}
